package com.mbc.web.common.client.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.HeadingElement;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.HTMLPanel;

public class Modal extends Composite {

	public static final int MODAL_LARGE = 1;
	public static final int MODAL_SMALL = 2;
	
	@UiField HTMLPanel modal_body;
	@UiField HTMLPanel myModal;
	@UiField HTMLPanel modalDialog;
	@UiField HeadingElement modal_title;
	
	private static ModalUiBinder uiBinder = GWT.create(ModalUiBinder.class);

	interface ModalUiBinder extends UiBinder<Widget, Modal> {
	}

	private CloseHandler<Modal> closeHandler = null;
	
	public void addCloseHandler(CloseHandler<Modal> closeHandler)
	{
		this.closeHandler = closeHandler;
	}
	
	public void runCloseHandler(){
		if(closeHandler != null)
			closeHandler.onClose(null);
	}
	
	public void setTitle(String title)
	{
		modal_title.setInnerText(title);
	}
	
	public Modal() {
		initWidget(uiBinder.createAndBindUi(this));
		
		myModal.getElement().setAttribute("aria-hidden", "true");
		myModal.getElement().setId("myModal");
	}
	
	public void show(Composite composite){
		this.modal_body.add(composite);
		RootPanel.get("rootBody").add(this);
		
		showModal();
	}
	
	public void show(Composite composite, int size){
		if(size == Modal.MODAL_LARGE)
			modalDialog.addStyleName("modal-lg");
		else if(size == Modal.MODAL_SMALL)
			modalDialog.addStyleName("modal-sm");
			
		show(composite);
	}
	
	private void close()
	{
		if(closeHandler != null)
			closeHandler.onClose(null);
		this.removeFromParent();
	}
	
	private native void showModal()/*-{
		var self = this;
		$wnd.$('#myModal').modal({
		  keyboard: false,
		  show:true
		});
		var callback = $entry(function(){
			self.@com.mbc.web.common.client.ui.Modal::close()();
		});
		$wnd.$('#myModal').on('hidden.bs.modal', callback);
	}-*/;
	
	private native void closeModal() /*-{
		$wnd.$('#myModal').modal('hide');
	}-*/;
}
